<template>
  <div class="question-input" :class="inputClasses">
    <!-- 输入框头部 -->
    <div v-if="showHeader" class="input-header">
      <div class="input-label">
        <span>{{ label }}</span>
        <el-tooltip v-if="showHelp" content="Ctrl+Enter 快速发送，Escape 清空内容">
          <el-icon class="help-icon"><QuestionFilled /></el-icon>
        </el-tooltip>
      </div>
      
      <div class="input-meta">
        <!-- 字符计数 -->
        <span class="char-counter" :class="charCounterClass">
          {{ currentLength }}/{{ maxLength }}
        </span>
        
        <!-- 输入模式切换 -->
        <el-tooltip content="切换输入模式">
          <el-button
            type="text"
            :icon="isMultiline ? 'Minus' : 'Plus'"
            @click="toggleInputMode"
            class="mode-toggle"
            size="small"
          />
        </el-tooltip>
      </div>
    </div>
    
    <!-- 输入框主体 -->
    <div class="input-body">
      <div class="input-wrapper">
        <!-- 文本输入框 -->
        <el-input
          ref="inputRef"
          v-model="inputValue"
          :type="isMultiline ? 'textarea' : 'text'"
          :placeholder="computedPlaceholder"
          :disabled="disabled"
          :maxlength="maxLength"
          :show-word-limit="false"
          :autosize="textareaAutosize"
          :resize="isMultiline ? 'vertical' : 'none'"
          class="input-field"
          @keydown="handleKeydown"
          @input="handleInput"
          @focus="handleFocus"
          @blur="handleBlur"
          @paste="handlePaste"
        />
        
        <!-- 输入建议 -->
        <transition name="slide-up">
          <div v-if="showSuggestions && suggestions.length > 0" class="input-suggestions">
            <div
              v-for="(suggestion, index) in suggestions"
              :key="index"
              :class="['suggestion-item', { active: activeSuggestionIndex === index }]"
              @click="applySuggestion(suggestion)"
              @mouseenter="activeSuggestionIndex = index"
            >
              <el-icon class="suggestion-icon"><ChatDotRound /></el-icon>
              <span class="suggestion-text">{{ suggestion }}</span>
            </div>
          </div>
        </transition>
      </div>
      
      <!-- 操作按钮区域 -->
      <div class="input-actions">
        <!-- 语音输入按钮 -->
        <el-tooltip v-if="enableVoice" content="语音输入">
          <el-button
            :type="isVoiceActive ? 'primary' : 'text'"
            :icon="isVoiceActive ? 'MicrophoneFilled' : 'Microphone'"
            @click="toggleVoiceInput"
            class="action-button voice-button"
            :class="{ 'voice-active': isVoiceActive }"
            circle
          />
        </el-tooltip>
        
        <!-- 附件上传按钮 -->
        <el-tooltip v-if="enableUpload" content="上传文件">
          <el-upload
            :show-file-list="false"
            :before-upload="handleFileUpload"
            accept=".txt,.md,.pdf,.doc,.docx"
            class="upload-wrapper"
          >
            <el-button
              type="text"
              icon="Paperclip"
              class="action-button"
              circle
            />
          </el-upload>
        </el-tooltip>
        
        <!-- 清空按钮 -->
        <el-tooltip content="清空内容 (Escape)">
          <el-button
            v-if="canClear"
            type="text"
            icon="Delete"
            @click="clearInput"
            class="action-button clear-button"
            circle
          />
        </el-tooltip>
        
        <!-- 发送按钮 -->
        <el-tooltip :content="sendButtonTooltip">
          <el-button
            type="primary"
            :icon="loading ? 'Loading' : 'Position'"
            :loading="loading"
            :disabled="!canSend"
            @click="handleSubmit"
            class="send-button"
            :class="{ 'send-ready': canSend }"
          >
            {{ sendButtonText }}
          </el-button>
        </el-tooltip>
      </div>
    </div>
    
    <!-- 输入框底部 -->
    <div v-if="showFooter" class="input-footer">
      <div class="input-tips">
        <!-- 快捷键提示 -->
        <transition name="fade">
          <span v-if="isFocused && !loading" class="shortcut-tip">
            按 <kbd>Ctrl</kbd> + <kbd>Enter</kbd> 快速发送
          </span>
        </transition>
        
        <!-- 错误提示 -->
        <transition name="slide-up">
          <span v-if="errorMessage" class="error-tip">
            <el-icon><WarningFilled /></el-icon>
            {{ errorMessage }}
          </span>
        </transition>
        
        <!-- 状态提示 -->
        <transition name="fade">
          <span v-if="statusMessage" class="status-tip" :class="statusType">
            <el-icon><component :is="statusIcon" /></el-icon>
            {{ statusMessage }}
          </span>
        </transition>
      </div>
      
      <!-- 输入历史 -->
      <div v-if="showHistory && inputHistory.length > 0" class="input-history">
        <el-dropdown trigger="click" @command="applyHistory">
          <el-button type="text" size="small" class="history-button">
            <el-icon><Clock /></el-icon>
            历史输入
          </el-button>
          <template #dropdown>
            <el-dropdown-menu class="history-menu">
              <el-dropdown-item
                v-for="(item, index) in inputHistory.slice(0, 10)"
                :key="index"
                :command="item"
                class="history-item"
              >
                <span class="history-text">{{ truncateText(item, 50) }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// Props
interface Props {
  modelValue?: string
  placeholder?: string
  label?: string
  maxLength?: number
  disabled?: boolean
  loading?: boolean
  autoFocus?: boolean
  showHeader?: boolean
  showFooter?: boolean
  showHelp?: boolean
  showHistory?: boolean
  enableVoice?: boolean
  enableUpload?: boolean
  multiline?: boolean
  suggestions?: string[]
  validateOnInput?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '输入您的问题...',
  label: '问题输入',
  maxLength: 2000,
  disabled: false,
  loading: false,
  autoFocus: false,
  showHeader: true,
  showFooter: true,
  showHelp: true,
  showHistory: true,
  enableVoice: false,
  enableUpload: false,
  multiline: false,
  suggestions: () => [],
  validateOnInput: true
})

// Emits
interface Emits {
  'update:modelValue': [value: string]
  submit: [value: string]
  clear: []
  focus: []
  blur: []
  'voice-input': [active: boolean]
  'file-upload': [file: File]
  'input-change': [value: string]
}

const emit = defineEmits<Emits>()

// 状态
const inputRef = ref()
const inputValue = ref(props.modelValue)
const isFocused = ref(false)
const isMultiline = ref(props.multiline)
const isVoiceActive = ref(false)
const showSuggestions = ref(false)
const activeSuggestionIndex = ref(-1)
const errorMessage = ref('')
const statusMessage = ref('')
const statusType = ref<'success' | 'warning' | 'info'>('info')
const inputHistory = ref<string[]>([])

// 计算属性
const inputClasses = computed(() => ({
  'question-input': true,
  'question-input--focused': isFocused.value,
  'question-input--disabled': props.disabled,
  'question-input--loading': props.loading,
  'question-input--error': !!errorMessage.value,
  'question-input--multiline': isMultiline.value,
  'question-input--voice-active': isVoiceActive.value
}))

const currentLength = computed(() => inputValue.value.length)

const charCounterClass = computed(() => ({
  'char-counter': true,
  'char-counter--warning': currentLength.value > props.maxLength * 0.8,
  'char-counter--error': currentLength.value >= props.maxLength,
  'char-counter--success': currentLength.value > 0 && currentLength.value <= props.maxLength * 0.8
}))

const canSend = computed(() => {
  return inputValue.value.trim().length > 0 && 
         currentLength.value <= props.maxLength && 
         !props.loading && 
         !props.disabled &&
         !errorMessage.value
})

const canClear = computed(() => {
  return inputValue.value.length > 0 && !props.disabled
})

const computedPlaceholder = computed(() => {
  if (props.disabled) return '输入已禁用'
  if (props.loading) return 'AI正在处理中...'
  return props.placeholder
})

const sendButtonText = computed(() => {
  if (props.loading) return '发送中'
  return '发送'
})

const sendButtonTooltip = computed(() => {
  if (!canSend.value) {
    if (inputValue.value.trim().length === 0) return '请输入内容'
    if (currentLength.value > props.maxLength) return `超出最大长度限制 (${props.maxLength})`
    if (props.disabled) return '输入已禁用'
    if (props.loading) return '正在处理中'
    if (errorMessage.value) return errorMessage.value
  }
  return 'Ctrl+Enter 快速发送'
})

const textareaAutosize = computed(() => ({
  minRows: 2,
  maxRows: 8
}))

const statusIcon = computed(() => {
  switch (statusType.value) {
    case 'success': return 'CircleCheckFilled'
    case 'warning': return 'WarningFilled'
    case 'info': return 'InfoFilled'
    default: return 'InfoFilled'
  }
})

// 方法
const handleInput = (value: string) => {
  inputValue.value = value
  emit('update:modelValue', value)
  emit('input-change', value)
  
  // 输入验证
  if (props.validateOnInput) {
    validateInput()
  }
  
  // 显示建议
  if (value.trim().length > 0 && props.suggestions.length > 0) {
    showSuggestions.value = true
  } else {
    showSuggestions.value = false
  }
}

const handleKeydown = (event: KeyboardEvent) => {
  // Ctrl+Enter 发送
  if (event.ctrlKey && event.key === 'Enter') {
    event.preventDefault()
    handleSubmit()
    return
  }
  
  // Escape 清空
  if (event.key === 'Escape') {
    event.preventDefault()
    clearInput()
    return
  }
  
  // 建议选择
  if (showSuggestions.value && props.suggestions.length > 0) {
    if (event.key === 'ArrowDown') {
      event.preventDefault()
      activeSuggestionIndex.value = Math.min(
        activeSuggestionIndex.value + 1,
        props.suggestions.length - 1
      )
      return
    }
    
    if (event.key === 'ArrowUp') {
      event.preventDefault()
      activeSuggestionIndex.value = Math.max(activeSuggestionIndex.value - 1, -1)
      return
    }
    
    if (event.key === 'Tab' && activeSuggestionIndex.value >= 0) {
      event.preventDefault()
      applySuggestion(props.suggestions[activeSuggestionIndex.value])
      return
    }
  }
  
  // Enter 发送（非多行模式）
  if (!isMultiline.value && event.key === 'Enter') {
    event.preventDefault()
    handleSubmit()
    return
  }
}

const handleFocus = () => {
  isFocused.value = true
  emit('focus')
}

const handleBlur = () => {
  isFocused.value = false
  showSuggestions.value = false
  activeSuggestionIndex.value = -1
  emit('blur')
}

const handlePaste = (event: ClipboardEvent) => {
  // 处理粘贴事件，可以在这里添加文件粘贴支持
  console.log('Paste event:', event)
}

const handleSubmit = () => {
  if (!canSend.value) return
  
  const value = inputValue.value.trim()
  if (value) {
    // 添加到历史记录
    addToHistory(value)
    
    // 发送消息
    emit('submit', value)
    
    // 清空输入
    inputValue.value = ''
    emit('update:modelValue', '')
    
    // 显示成功状态
    showStatus('发送成功', 'success')
    
    // 聚焦输入框
    nextTick(() => {
      focusInput()
    })
  }
}

const clearInput = () => {
  inputValue.value = ''
  emit('update:modelValue', '')
  emit('clear')
  clearError()
  clearStatus()
  focusInput()
}

const focusInput = () => {
  if (inputRef.value) {
    inputRef.value.focus()
  }
}

const toggleInputMode = () => {
  isMultiline.value = !isMultiline.value
  nextTick(() => {
    focusInput()
  })
}

const toggleVoiceInput = () => {
  isVoiceActive.value = !isVoiceActive.value
  emit('voice-input', isVoiceActive.value)
  
  if (isVoiceActive.value) {
    showStatus('语音输入已激活', 'info')
  } else {
    clearStatus()
  }
}

const handleFileUpload = (file: File) => {
  // 文件大小检查
  const maxSize = 10 * 1024 * 1024 // 10MB
  if (file.size > maxSize) {
    showError('文件大小不能超过 10MB')
    return false
  }
  
  // 文件类型检查
  const allowedTypes = ['text/plain', 'text/markdown', 'application/pdf', 'application/msword']
  if (!allowedTypes.includes(file.type)) {
    showError('不支持的文件类型')
    return false
  }
  
  emit('file-upload', file)
  showStatus(`文件 "${file.name}" 上传成功`, 'success')
  
  return false // 阻止自动上传
}

const applySuggestion = (suggestion: string) => {
  inputValue.value = suggestion
  emit('update:modelValue', suggestion)
  showSuggestions.value = false
  activeSuggestionIndex.value = -1
  focusInput()
}

const addToHistory = (value: string) => {
  // 避免重复
  const index = inputHistory.value.indexOf(value)
  if (index > -1) {
    inputHistory.value.splice(index, 1)
  }
  
  // 添加到开头
  inputHistory.value.unshift(value)
  
  // 限制历史记录数量
  if (inputHistory.value.length > 50) {
    inputHistory.value = inputHistory.value.slice(0, 50)
  }
  
  // 保存到本地存储
  localStorage.setItem('question-input-history', JSON.stringify(inputHistory.value))
}

const applyHistory = (item: string) => {
  inputValue.value = item
  emit('update:modelValue', item)
  focusInput()
}

const loadHistory = () => {
  try {
    const saved = localStorage.getItem('question-input-history')
    if (saved) {
      inputHistory.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('Failed to load input history:', error)
  }
}

const validateInput = () => {
  clearError()
  
  const value = inputValue.value.trim()
  
  // 长度检查
  if (value.length > props.maxLength) {
    showError(`内容长度不能超过 ${props.maxLength} 个字符`)
    return false
  }
  
  // 内容检查（可以添加更多验证规则）
  if (value.length > 0 && value.length < 2) {
    showError('问题内容过短，请输入更详细的描述')
    return false
  }
  
  return true
}

const showError = (message: string) => {
  errorMessage.value = message
  setTimeout(clearError, 5000)
}

const clearError = () => {
  errorMessage.value = ''
}

const showStatus = (message: string, type: 'success' | 'warning' | 'info' = 'info') => {
  statusMessage.value = message
  statusType.value = type
  setTimeout(clearStatus, 3000)
}

const clearStatus = () => {
  statusMessage.value = ''
}

const truncateText = (text: string, maxLength: number) => {
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== inputValue.value) {
    inputValue.value = newValue
  }
})

// 生命周期
onMounted(() => {
  // 加载历史记录
  loadHistory()
  
  // 自动聚焦
  if (props.autoFocus) {
    nextTick(() => {
      focusInput()
    })
  }
})

// 暴露方法
defineExpose({
  focus: focusInput,
  clear: clearInput,
  validate: validateInput
})
</script>

<style lang="scss" scoped>
.question-input {
  background: var(--bg-color);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-base);
  transition: var(--transition-base);
  
  &.question-input--focused {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
  
  &.question-input--disabled {
    background: var(--bg-color-light);
    border-color: var(--border-color-light);
    cursor: not-allowed;
  }
  
  &.question-input--error {
    border-color: var(--danger-color);
    box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
  }
  
  &.question-input--loading {
    pointer-events: none;
    opacity: 0.8;
  }
  
  &.question-input--voice-active {
    border-color: var(--success-color);
    box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
  }
}

// 输入框头部
.input-header {
  @include flex-between;
  padding: var(--spacing-sm) var(--spacing-md);
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-color-light);
}

.input-label {
  @include flex-start;
  gap: var(--spacing-xs);
  font-size: var(--font-size-small);
  font-weight: 500;
  color: var(--text-color-primary);
  
  .help-icon {
    color: var(--text-color-secondary);
    cursor: help;
    
    &:hover {
      color: var(--primary-color);
    }
  }
}

.input-meta {
  @include flex-center;
  gap: var(--spacing-sm);
}

.char-counter {
  font-size: var(--font-size-extra-small);
  color: var(--text-color-secondary);
  
  &.char-counter--warning {
    color: var(--warning-color);
  }
  
  &.char-counter--error {
    color: var(--danger-color);
    font-weight: 600;
  }
  
  &.char-counter--success {
    color: var(--success-color);
  }
}

.mode-toggle {
  width: 24px;
  height: 24px;
  
  &:hover {
    color: var(--primary-color);
  }
}

// 输入框主体
.input-body {
  position: relative;
  padding: var(--spacing-md);
}

.input-wrapper {
  position: relative;
  @include flex-start;
  gap: var(--spacing-sm);
}

.input-field {
  flex: 1;
  
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none;
    background: transparent;
    padding: 0;
  }
  
  :deep(.el-textarea__inner) {
    border: none;
    box-shadow: none;
    background: transparent;
    padding: 0;
    resize: vertical;
  }
  
  :deep(.el-input__inner) {
    font-size: var(--font-size-base);
    line-height: 1.5;
    
    &::placeholder {
      color: var(--text-color-placeholder);
    }
  }
}

// 输入建议
.input-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: var(--bg-color);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-base);
  box-shadow: var(--box-shadow-base);
  z-index: var(--z-index-popper);
  max-height: 200px;
  overflow-y: auto;
  @include scrollbar;
}

.suggestion-item {
  @include flex-start;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm) var(--spacing-md);
  cursor: pointer;
  transition: var(--transition-base);
  border-bottom: 1px solid var(--border-color-light);
  
  &:last-child {
    border-bottom: none;
  }
  
  &:hover,
  &.active {
    background: var(--primary-color-lighter);
    color: var(--primary-color);
  }
  
  .suggestion-icon {
    color: var(--text-color-secondary);
    font-size: 14px;
    flex-shrink: 0;
  }
  
  .suggestion-text {
    @include text-ellipsis;
    font-size: var(--font-size-small);
  }
}

// 操作按钮区域
.input-actions {
  @include flex-center;
  gap: var(--spacing-xs);
  flex-shrink: 0;
}

.action-button {
  width: 32px;
  height: 32px;
  
  &.voice-button {
    &.voice-active {
      color: var(--success-color);
      background: var(--success-color-lighter);
      
      @include pulse-animation;
    }
  }
  
  &.clear-button {
    &:hover {
      color: var(--danger-color);
    }
  }
}

.upload-wrapper {
  .el-button {
    width: 32px;
    height: 32px;
  }
}

.send-button {
  min-width: 80px;
  height: 36px;
  
  &.send-ready {
    @include button-hover;
  }
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

// 输入框底部
.input-footer {
  @include flex-between;
  padding: var(--spacing-sm) var(--spacing-md);
  border-top: 1px solid var(--border-color);
  background: var(--bg-color-light);
}

.input-tips {
  @include flex-start;
  gap: var(--spacing-md);
  flex: 1;
}

.shortcut-tip {
  font-size: var(--font-size-extra-small);
  color: var(--text-color-secondary);
  
  kbd {
    padding: 2px 4px;
    background: var(--bg-color-dark);
    border: 1px solid var(--border-color);
    border-radius: 2px;
    font-size: inherit;
    font-family: inherit;
  }
}

.error-tip {
  @include flex-start;
  gap: var(--spacing-xs);
  font-size: var(--font-size-extra-small);
  color: var(--danger-color);
}

.status-tip {
  @include flex-start;
  gap: var(--spacing-xs);
  font-size: var(--font-size-extra-small);
  
  &.success {
    color: var(--success-color);
  }
  
  &.warning {
    color: var(--warning-color);
  }
  
  &.info {
    color: var(--info-color);
  }
}

// 输入历史
.input-history {
  flex-shrink: 0;
}

.history-button {
  font-size: var(--font-size-extra-small);
  color: var(--text-color-secondary);
  
  &:hover {
    color: var(--primary-color);
  }
}

.history-menu {
  max-width: 300px;
}

.history-item {
  .history-text {
    @include text-ellipsis;
    font-size: var(--font-size-small);
  }
}

// 动画
.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from,
.slide-up-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 响应式适配
@include respond-to(md) {
  .input-header,
  .input-footer {
    padding: var(--spacing-xs) var(--spacing-sm);
  }
  
  .input-body {
    padding: var(--spacing-sm);
  }
  
  .input-actions {
    gap: var(--spacing-xs);
  }
  
  .action-button {
    width: 28px;
    height: 28px;
  }
  
  .send-button {
    min-width: 60px;
    height: 32px;
  }
}
</style>